<template>
  <div class="back_white">
    <el-row :gutter="20">
      <el-col :span="6">
        <div>
          <el-input placeholder="请输入搜索内容"></el-input>
        </div>
      </el-col>
      <el-col :span="2">
        <div>
          <el-button>查询</el-button>
        </div>
      </el-col>
      <el-col :span="2">
        <div>
          <el-button @click="addDialog=true">新增</el-button>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content ep-bg-purple"/>
      </el-col>
    </el-row>
  </div>
  <div style="margin-top: 20px">
    <el-table :data="brands" border style="width: 100%;height: 500px">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="品牌logo" width="140">
        <template #default="scope">
          <el-image style="width: 40px; height: 40px" :src="$imgBaseUrl+scope.row.logo" :fit="fill"/>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="编号" width="180"/>
      <el-table-column prop="name" label="名称" width="180"/>
      <el-table-column prop="sort" label="排序"/>
      <el-table-column label="状态">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-switch v-model="scope.row.state" :active-value="0" :inactive-value="1" active-text="启用"
                       inactive-text="禁用" @change="changeState(scope.row)"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="describes" label="介绍"/>
      <el-table-column label="操作">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-text type="danger" @click="openAsso(scope.row)">关联分类</el-text>
            <el-divider direction="vertical" border-style="dashed"/>
            <el-text type="danger" @click="del(scope.row)">删除</el-text>
            <el-divider direction="vertical" border-style="dashed"/>
            <el-text type="danger">修改</el-text>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div style="margin-top: 20px">
    <el-pagination
        :page-size="pageInfo.pageSize"
        :pager-count="8"
        layout="prev, pager, next"
        :total="pageInfo.totals"
    />
  </div>
  <div>
    <el-dialog
        v-model="addDialog"
        title="新增"
        width="30%"
        ref="ruleFormRef"
        @close="formRef.resetFields()"
        draggable
    >
      <el-form :model="addFrom" :rules="rules" label-width="auto" ref="formRef">
        <el-form-item label="logo" prop="logo">
          <el-upload
              name="files"
              class="avatar-uploader"
              :action="$upFile"
              :limit="1"
              :data="fileInfoVo"
              :headers="header"
              :file-list="imgShow"
              :on-success="handleAvatarSuccess"
          >
            <el-button>上传logo图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="addFrom.name"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="addFrom.state" :active-value="0" :inactive-value="1" active-text="启用"
                     inactive-text="禁用"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="addFrom.sort"/>
        </el-form-item>
        <el-form-item label="品牌介绍" prop="describes">
          <el-input type="textarea" v-model="addFrom.describes"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button @click="addSubmit(formRef)">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="assoCateDialog" title="分类关联" width="50%" draggable @close="assoCateRef.resetFields()">
      <div>
        <div>
          <el-form :model="assoBrandCategory" ref="assoCateRef" inline>
            <el-form-item label="三级分类" prop="categoryId">
              <el-cascader v-model="assoBrandCategory.categoryId" :options="categoryList"
                           :emitPath="false"
                           @visible-change="getAllCategory" :props="defaultProps" clearable/>
            </el-form-item>
            <el-form-item>
              <el-button @click="sumbitCateAsso(assoCateRef)"
                         :disabled="assoBrandCategory.categoryId==null ||assoBrandCategory.categoryId==''"
              >新增关联
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="assoCateList" style="width: 100%">
          <el-table-column prop="id" label="编号" width="180"/>
          <el-table-column prop="brandName" label="品牌名" width="180"/>
          <el-table-column prop="categoryName" label="分类名称"/>
        </el-table>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="assoCateDialog = false">取消</el-button>
        <el-button type="primary" @click="assoCateDialog = false">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>

  </div>

</template>

<script setup>
import {reactive, ref, onMounted} from "vue"
import {addBrand, getBrands, delBrand, modifyBrand, addBrandCategory, getBrandCategory} from '@/api/home/brand/brand'
import {getToken} from '@/util/token/tokenUtil'
import {getAllCategoryToTree} from '@/api/home/goods/category'
import {ElMessage, ElMessageBox} from 'element-plus'

let brands = ref([])
let addDialog = ref(false)
let assoCateDialog = ref()
let formRef = ref()
let assoCateList = ref([])
let categoryList = ref([])
let assoCateRef = ref()
let imgShow=ref([])
let addFrom = ref({
  name: '',
  logo: '',
  describes: '',
  state: 0,
  sort: ''
})
let fileInfoVo = ref({
  bucketName: 'goods',
  folderName: 'brandlogo',
  fileName: '',
  filePath: ''
})
let pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  totals: ''
})
let assoBrandCategory = ref({
  categoryId: '',
  brandId: '',
  brandName: '',
  categoryName: ''
})

const ruleFormRef = ref(null)
const defaultProps = {
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
}

/*页面挂载完毕，初始化数据*/
onMounted(() => {
  getList(1, 10)
})

function getAllCategory() {
  getAllCategoryToTree().then(res => {
    categoryList.value = res.data
  })
}

/*提交新增*/
function addSubmit(formref) {
  formref.validate((valid) => {
    if (valid) {
      addBrand(addFrom.value).then(res => {
        addFrom.value.logo = res.data
        getList(pageInfo.value.pageNum, pageInfo.value.pageSize)//刷新
        addDialog.value = false
      })
    } else return false
  })
}

function handleAvatarSuccess(res) {
  addFrom.value.logo = res.data
}

/*获取品牌列表*/
async function getList(pageNum, pageSize) {
  let res = await getBrands(pageNum, pageSize);
  brands.value = res.data.records
  /*分页信息封装*/
  pageInfo.value.totals = res.data.total - 0
}

function openAsso(node) {
  assoBrandCategory.value.brandId = node.id
  assoBrandCategory.value.brandName = node.name
  getBrandCategory(assoBrandCategory.value.brandId).then((res) => {
    assoCateList.value = res.data
  })
  assoCateDialog.value = true
}

function sumbitCateAsso(r) {
  r.validate((v) => {
    if (v) {
      addBrandCategory(assoBrandCategory.value).then(() => {
        getBrandCategory(assoBrandCategory.value.brandId).then((res) => {
          assoCateList.value = res.data
        })
      })
    } else return false
  })
}

/*修改状态*/
function changeState(brand) {
  modifyBrand(brand).then(() => {
    getList(pageInfo.value.pageNum, pageInfo.value.pageSize)//刷新
  })
}

/*删除*/
function del(node) {
  /*确认框*/
  ElMessageBox.confirm(
      `你确定要删除${node.name}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    /*发送删除请求*/
    delBrand(node.id)
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消成功',
    })
  })
}

const header = {
  token: getToken('token')
}
let rules = reactive({
  name: [
    {required: true, message: '请输入品牌名称', trigger: 'blur'},
  ],
  logo: [{
    required: true, message: '请上传logo图片', trigger: 'blur'
  }],
  describes: [
    {required: true, message: '品牌介绍不能为空', trigger: 'blur'},
  ]
})

</script>

<style scoped>

</style>
